package com.oh.handler;

import com.oh.core.common.constant.CommandEnum;
import com.oh.core.common.constant.SerializationAlgorithm;
import com.oh.core.common.utils.MessageUtils;
import com.oh.core.entity.MessageEntity;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;

/**
 * 协议bean
 */
public class ProtocolClientHandler extends SimpleChannelInboundHandler<MessageEntity> {

    private final Logger log = LoggerFactory.getLogger(ProtocolClientHandler.class);

    int magic = 5710;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageEntity msg) throws Exception {
        System.out.println(msg);
        System.out.println(Arrays.toString(msg.toMsgBytes()));
        log.info("接收到服务器消息：{}", new String(msg.getBody()));
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String msg = "客户端消息:已建立连接准备...";
        System.out.println(msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//        cause.printStackTrace();
        System.out.println(cause.getMessage());
        ctx.close();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        System.out.println("触发心跳!!!!!");
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            if (state == IdleState.WRITER_IDLE) {
                // write heartbeat to server
                ctx.writeAndFlush(new MessageEntity(CommandEnum.HEART_BEAT.getCommand(), magic,"HEART_BEAT".getBytes()).toMsgBytes());
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}
